package com.epam.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.epam.command.logic.Command;
import com.epam.command.logic.CommandFactory;
import com.epam.util.ConfigurationManager;

public class Controller extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = Logger.getLogger(Controller.class);

	public Controller() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		request.getRequestDispatcher(processRequest(request, response)).forward(request, response);
		
		
		
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) {
		String page = processRequest(request, response);
		System.out.println(page);
		try {
		if (page.equals(ConfigurationManager.getConfig(ConfigurationManager.OPERATION_SUCCESSFUL))) {
			response.sendRedirect(page);
		} else {
			
			request.getRequestDispatcher(page).forward(request, response);
		}
		} catch (IOException | ServletException e) {
			LOG.error(e);
		}

	}
	
	private String processRequest(HttpServletRequest request,
			HttpServletResponse response) {
		
		String page;
		Command command = CommandFactory.INSTANCE.getCommand(request);
		page = command.execute(request, response);
		return page;
		
	}

}
